package com.example.barrage.config;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class NettyConfig {

    @Value("${netty.port:8090}")
    private int port;

    @Value("${netty.boss.thread.count:1}")
    private int bossCount;

    @Value("${netty.worker.thread.count:4}")
    private int workerCount;

    @Value("${netty.so.keepalive:true}")
    private boolean keepAlive;

    @Value("${netty.so.backlog:128}")
    private int backlog;
    
    @Autowired
    private NettyServerInitializer nettyServerInitializer;

    @Bean(name = "serverBootstrap")
    public ServerBootstrap bootstrap() {
        ServerBootstrap b = new ServerBootstrap();
        b.group(bossGroup(), workerGroup())
                .channel(NioServerSocketChannel.class)
                .handler(new LoggingHandler(LogLevel.DEBUG))
                .childHandler(nettyServerInitializer);
        b.option(ChannelOption.SO_BACKLOG, backlog);
        b.childOption(ChannelOption.SO_KEEPALIVE, keepAlive);
        return b;
    }

    @Bean(name = "bossGroup", destroyMethod = "shutdownGracefully")
    public NioEventLoopGroup bossGroup() {
        return new NioEventLoopGroup(bossCount);
    }

    @Bean(name = "workerGroup", destroyMethod = "shutdownGracefully")
    public NioEventLoopGroup workerGroup() {
        return new NioEventLoopGroup(workerCount);
    }
}